#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
RAG智能对话机器人演示 - 修复版本
添加了完整的错误处理和调试信息
"""

import time
import traceback


def safe_import_rag():
    """安全导入RAG模块"""
    try:
        from tools.RAGChatBot import RAGChatBot
        print("✅ RAG模块导入成功")
        return RAGChatBot
    except ImportError as e:
        if "pymilvus" in str(e):
            print("❌ 缺少pymilvus依赖包")
            print("请安装: pip install pymilvus>=2.3.0")
        elif "requests" in str(e):
            print("❌ 缺少requests依赖包") 
            print("请安装: pip install requests>=2.31.0")
        else:
            print(f"❌ 导入RAG模块失败: {e}")
        return None
    except Exception as e:
        print(f"❌ 导入RAG模块时出现未知错误: {e}")
        traceback.print_exc()
        return None


def safe_chat(bot, question):
    """安全的聊天方法调用，确保返回正确格式"""
    try:
        print(f"🔵 调用chat方法: '{question}'")
        result = bot.chat(question)
        
        print(f"🔵 chat方法返回: {type(result)}")
        
        if result is None:
            print("❌ chat方法返回None")
            return "chat方法返回None", []
        
        if not isinstance(result, tuple):
            print(f"❌ chat方法返回非元组类型: {type(result)}")
            return f"返回类型错误: {type(result)}", []
        
        if len(result) != 2:
            print(f"❌ chat方法返回元组长度不对: {len(result)}")
            return f"元组长度错误: {len(result)}", []
        
        response, sources = result
        print(f"✅ chat方法成功解包: response={type(response)}, sources={type(sources)}")
        
        return response, sources
        
    except ValueError as e:
        if "not enough values to unpack" in str(e):
            print(f"❌ 元组解包错误: {e}")
            return f"解包错误: {e}", []
        else:
            print(f"❌ 值错误: {e}")
            return f"值错误: {e}", []
    except Exception as e:
        print(f"❌ chat方法调用异常: {e}")
        traceback.print_exc()
        return f"调用异常: {e}", []


def demo_basic_chat():
    """基础对话演示 - 增强错误处理"""
    print("=" * 60)
    print("基础对话演示")
    print("=" * 60)
    
    # 1. 导入模块
    RAGChatBot = safe_import_rag()
    if not RAGChatBot:
        return None
    
    # 2. 创建机器人实例
    print("\n🚀 创建RAG机器人实例...")
    try:
        bot = RAGChatBot(
            ollama_url="http://172.26.32.1:11434",
            milvus_collection="workspace_files",
            default_model="deepseek-r1:14b"
        )
        print("✅ RAG机器人实例创建成功")
    except Exception as e:
        print(f"❌ 创建RAG机器人实例失败: {e}")
        traceback.print_exc()
        return None
    
    # 3. 初始化
    print("\n🔧 初始化RAG系统...")
    try:
        if not bot.initialize():
            print("❌ RAG系统初始化失败")
            return None
        print("✅ RAG系统初始化成功")
    except Exception as e:
        print(f"❌ 初始化过程中出现异常: {e}")
        traceback.print_exc()
        return None
    
    # 4. 测试对话
    demo_questions = [
        "有哪些Python文件？",
        "最近修改的配置文件是什么？",
        "帮我找找文档类的文件"
    ]
    
    print(f"\n💬 开始测试对话 ({len(demo_questions)}个问题):")
    print("-" * 60)
    
    for i, question in enumerate(demo_questions, 1):
        print(f"\n[问题 {i}] 👤: {question}")
        
        start_time = time.time()
        response, sources = safe_chat(bot, question)
        elapsed = time.time() - start_time
        
        print(f"🤖: {response}")
        
        if sources:
            print(f"\n📚 参考文件 ({len(sources)}个):")
            for j, source in enumerate(sources[:3], 1):  # 只显示前3个
                try:
                    print(f"   {j}. {source['file_name']} (相似度: {source['similarity_score']:.3f})")
                except (KeyError, TypeError) as e:
                    print(f"   {j}. 源文件信息格式错误: {e}")
        else:
            print("📚 无参考文件")
        
        print(f"⏱️ 耗时: {elapsed:.2f}秒")
        print("-" * 60)
        
        # 短暂停顿
        time.sleep(1)
    
    return bot


def demo_system_stats(bot):
    """系统统计演示"""
    if not bot:
        print("⚠️ 机器人实例不存在，跳过统计演示")
        return
    
    print("=" * 60)
    print("系统统计演示")
    print("=" * 60)
    
    try:
        stats = bot.get_stats()
        print("📊 系统统计信息:")
        print(f"   当前模型: {stats.get('current_model', 'N/A')}")
        print(f"   对话消息数: {stats.get('chat_messages', 0)}")
        print(f"   文件索引数: {stats.get('milvus_entities', 0):,}")
        
        config = stats.get('config', {})
        print(f"   最大检索文件数: {config.get('max_context_files', 'N/A')}")
        print(f"   最大上下文长度: {config.get('max_context_length', 'N/A')}")
        print(f"   相似度阈值: {config.get('similarity_threshold', 'N/A')}")
        
    except Exception as e:
        print(f"❌ 获取统计信息失败: {e}")
        traceback.print_exc()


def demo_model_info(bot):
    """模型信息演示"""
    if not bot:
        print("⚠️ 机器人实例不存在，跳过模型信息演示")
        return
    
    print("=" * 60)
    print("模型信息演示")
    print("=" * 60)
    
    try:
        models = bot.get_available_models()
        print(f"📋 可用模型 ({len(models)}个):")
        for i, model in enumerate(models, 1):
            current = " (当前)" if model == bot.current_model else ""
            print(f"   {i}. {model}{current}")
    except Exception as e:
        print(f"❌ 获取模型信息失败: {e}")
        traceback.print_exc()


def main():
    """主演示函数 - 增强版"""
    print("🤖 RAG智能对话机器人演示 - 增强版")
    print("提供完整的错误处理和诊断信息")
    print("=" * 80)
    
    try:
        # 运行基础对话演示
        bot = demo_basic_chat()
        
        # 运行其他演示
        demo_system_stats(bot)
        demo_model_info(bot)
        
        print("=" * 80)
        if bot:
            print("🎉 演示完成，RAG系统运行正常")
        else:
            print("⚠️ 演示完成，但RAG系统初始化失败")
        
    except KeyboardInterrupt:
        print("\n⏹️ 演示被用户中断")
    except Exception as e:
        print(f"❌ 演示过程中出现未捕获异常: {e}")
        traceback.print_exc()
    finally:
        print("🔚 演示程序结束")


if __name__ == "__main__":
    main()